﻿using System;
using System.Collections;
using UnityEngine;
using UnityEngine.SceneManagement;

namespace TinyAsset
{
    public class AssetOperationHandle : IEnumerator
    {
        AssetLoader assetLoader;

        public UnityEngine.Object asset => IsValid() ? assetLoader.asset : null;

        public Scene scene => IsValid() ? assetLoader.scene : default;

        public bool allowSceneActivation
        {
            get
            {
                if (IsValid())
                    return assetLoader.allowSceneActivation;
                return _allowSceneActivation;
            }
            set
            {
                if (IsValid())
                    assetLoader.allowSceneActivation = value;
                _allowSceneActivation = value;
            }
        }

        bool _allowSceneActivation = true;

        public AssetOperationHandle(AssetLoader loader)
        {
            assetLoader = loader;
            assetLoader.allowSceneActivation = _allowSceneActivation;
            assetLoader.onCompleted += (h) => {
                if(onCompleted != null)
                {
                    onCompleted(this);
                    onCompleted = null;
                }
            };
        }

        public bool IsDone => !IsValid() || assetLoader.IsDone;

        public bool IsValid() { return assetLoader != null; }

        public void Release()
        {
            if (assetLoader != null)
            {
                ResourceManager.Instance.UnloadAsset(assetLoader.Key);
                assetLoader = null;
            }
        }

        public System.Threading.Tasks.Task Task => IsValid() ? assetLoader.Task : null;

        public event Action<AssetOperationHandle> onCompleted;

        object IEnumerator.Current => null;

        bool IEnumerator.MoveNext() { return !IsDone; }

        void IEnumerator.Reset() { }
    }
}